package heartlogic

import (
	"context"
	"strconv"
	"yunzhan/common/models"

	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type PingLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PingLogic {
	return &PingLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PingLogic) Ping(in *agent.PingRequest) (*agent.PingResponse, error) {
	// 获取心跳信息
	heartbeatInfo, err := models.GetHeartbeatInfo()
	if err != nil {
		logx.Errorf("Failed to get heartbeat info: %v", err)
		return nil, err
	}

	// 构造ResourceInfo字段，预先分配空间
	resourceInfo := make(map[string]string, 8)
	resourceInfo["agentID"] = heartbeatInfo.AgentId
	resourceInfo["hostName"] = heartbeatInfo.HostName
	resourceInfo["ipAddress"] = heartbeatInfo.IPAddress
	resourceInfo["status"] = strconv.FormatBool(heartbeatInfo.Status)
	resourceInfo["cpuUsage"] = strconv.FormatFloat(heartbeatInfo.CPUUsage, 'f', 2, 64)
	resourceInfo["memoryUsage"] = strconv.FormatFloat(heartbeatInfo.MemoryUsage, 'f', 2, 64)
	resourceInfo["diskSpace"] = strconv.FormatFloat(heartbeatInfo.DiskSpace, 'f', 2, 64)
	resourceInfo["processCount"] = strconv.Itoa(heartbeatInfo.ProcessCount)
	resourceInfo["lastHeartbeat"] = heartbeatInfo.LastHeartbeat

	return &agent.PingResponse{
		Healthy:      true,
		ResourceInfo: resourceInfo,
	}, nil
}
